from django.contrib.auth import get_user_model
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.hashers import make_password
from django.db import transaction

User = get_user_model()


class AdminResetPasswordView(APIView):
    permission_classes = [IsAdminUser]

    @transaction.atomic
    def post(self, request, user_id):
        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return Response({
                "error": "用户不存在"
            }, status=status.HTTP_400_BAD_REQUEST)
        # 重置密码,这里使用make_password来加密密码
        user.password = make_password(f"{user.username}123456")
        user.save()
        # 返回成功响应
        return Response({
            'message': f'密码已重置 ID: {user_id}'
        }, status=status.HTTP_200_OK)
